package com.wxw.BaseLibrary.http;

import android.content.Context;
import com.wxw.BaseLibrary.dialog.WaitingDialog;
import com.wxw.BaseLibrary.tool.Timeout;
import com.yolanda.nohttp.OnResponseListener;
import com.yolanda.nohttp.Request;
import com.yolanda.nohttp.Response;

/**
 * Created by david on 2016/5/6.
 */
public class HttpResponseListener<T> implements OnResponseListener<T> {
    private Context context;
    /**
     * Dialog
     */
    private WaitingDialog mWaitDialog;

    /**
     * 当前请求
     */
    private Request<?> mRequest;

    /**
     * 结果回调
     */
    private HttpListener<T> callback;

    /**
     * 是否显示dialog
     */
    private boolean isLoading;

    /**
     * @param context      context用来实例化dialog
     * @param request      请求对象
     * @param httpCallback 回调对象
     * @param canCancel    是否允许用户取消请求
     * @param isLoading    是否显示dialog
     */
    public HttpResponseListener(Context context, Request<?> request, HttpListener<T> httpCallback, boolean canCancel, boolean isLoading) {
        this.mRequest = request;
        this.context = context;
        this.callback = httpCallback;
        this.isLoading = isLoading;
    }

    /**
     * 开始请求, 这里显示一个dialog
     */
    @Override
    public void onStart(int what) {
        if (isLoading) {
            mWaitDialog = new WaitingDialog(context, "Is requesting data,please wait...", 300, new Timeout.OnTimeoutListener() {
                @Override
                public void onTimeout(Object sender, int time) {
                    mRequest.cancel(true);
                }
            });
        }
    }

    /**
     * 结束请求, 这里关闭dialog
     */
    @Override
    public void onFinish(int what) {
        if (isLoading && mWaitDialog != null) {
            mWaitDialog.stop();
        }
    }

    /**
     * 成功回调
     */
    @Override
    public void onSucceed(int what, Response<T> response) {
        if (callback != null) {
            callback.onSucceed(what, response);
        }
    }

    /**
     * 失败回调
     */
    @Override
    public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
        if (callback != null) {
            callback.onFailed(what, url, tag, exception.getMessage(), responseCode, networkMillis);
        }
    }
}
